<template>
  <div id="org">
    <el-breadcrumb v-if="flag==='Admin'" separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/staffing' }">机构编制管理</el-breadcrumb-item>
      <el-breadcrumb-item>机构编制信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-breadcrumb v-if="flag==='admin'" separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/staffing' }">机构编制管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/staffing/fill' }">填报管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ showTitle }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-breadcrumb v-if="flag==='user'" separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item>机构编制管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div id="orgTree" v-show="treeShow">
      <el-scrollbar style="height: calc(100% + 16px);">
        <div v-if="flag === 'user'" style="padding: 10px;">
          <div v-if="currentUnitStatus.remarks" style="margin-bottom: 6px;">填报说明：{{ currentUnitStatus.remarks }}</div>
          <el-button style="width: 100%;" type="success" :loading="btnLoading" @click="submit">提交</el-button>
        </div>
        <el-tree
          node-key="allId"
          ref="staffingTree"
          class="filter-tree"
          style="clear: both;"
          :data="treedata"
          :render-content="renderContent"
          :default-expanded-keys="[0, 1, 2, 3, '2-1', '2-2', '2-3']"
          :empty-text="loadingtext"
          :expand-on-click-node="false"
          @current-change="currentChangeHandler"
          >
        </el-tree>
      </el-scrollbar>
    </div>
    <div id="treebtn" @click="showtree()" :class="btnStyle"></div>
    <div id="orgdetail" :style="detailStyle">
      <h1 style="margin-top: 0">
        <span>{{ orgName }}</span>
        <span v-if="isShowText && flag!=='user'" style="color: red; font-weight: bolder;">{{ isShowText }}</span>
      </h1>
      <StaffingDetail
        v-if="jgsyCode && type"
        :jgsyCode='jgsyCode'
        :jgsyCodeMinistry='jgsyCodeMinistry'
        :flag="flag"
        :orgName="orgName"
        :type="type"
        :dClass="dClass"
        :historyTableName="historyTableName"
        :infoTableName="infoTableName"
        :sourceTable="sourceTable"
      >
      </StaffingDetail>
    </div>
  </div>
</template>

<script>
import StaffingDetail from './Detail.vue'

export default {
  components: {
    StaffingDetail
  },
  data () {
    return {
      currentUnitStatus: {},
      btnLoading: false,
      jgsyCode: null,
      jgsyCodeMinistry: null,
      flag: null,
      type: null,
      dClass: null,
      orgName: '请选择单位或部门',
      historyTableName: null,
      infoTableName: null,
      sourceTable: null,
      treedata: [],
      detailStyle: {
        margin: '0 0 0 280px',
        width: 'calc(100% - 290px)'
      },
      btnStyle: 'treebtn',
      treeShow: true,
      loadingtext: '正在加载...',
      showTitle: '',
      isShowText: ''
    }
  },
  mounted () {
    this.jgsyCode = this.$route.query.jgsyCode
    this.flag = this.$route.query.flag
    if (this.flag === 'user') {
      this.getCurrentUnitStatus()
    } else if (this.jgsyCode && this.flag === 'admin') {
      this.getOrgTreeByJgsyCode()
    } else {
      this.getOrgTreeJson()
    }
  },
  methods: {
    // 获取机构编制管理填报状态
    getCurrentUnitStatus () {
      this.$http
        .get(this.$http.defaults.headcountAPI + `api/busUnit/getCurrentUnitStatus`)
        .then(response => {
          if (response.data.success === true) {
            this.currentUnitStatus = response.data.result
            if (this.currentUnitStatus.status !== 0) {
              this.$router.back()
            } else {
              this.jgsyCode = this.currentUnitStatus.jgsyCode
              // 2025-2-20增加处理：如果机关司局，人员表jgsyCode为自然资源部的code，需要增加jgsyCodeMinistry变量，在原基础上移除最后一位，供机关司局查询人员时使用
              if (this.currentUnitStatus.unitTypeName === '机关司局') {
                let arr = this.jgsyCode.split('-')
                arr.pop()
                this.jgsyCodeMinistry = arr.join('-')
                console.log(this.jgsyCodeMinistry)
              }
              this.getOrgTreeByJgsyCode()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    // 根据jgsyCode获取单位树
    getOrgTreeByJgsyCode () {
      this.loadingtext = '正在加载...'
      this.$http
        .get(this.$http.defaults.headcountAPI + `api/busUnit/getOrgTreeByJgsyCode?jgsyCode=${this.jgsyCode}`)
        .then(response => {
          if (response.data.success === true) {
            this.showTitle = response.data.result.name
            this.treedata = [response.data.result]
            this.currentChangeHandler(this.treedata[0])
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    // 获取单位完整树状结构
    getOrgTreeJson () {
      this.loadingtext = '正在加载...'
      this.$http
        .get(this.$http.defaults.headcountAPI + `api/busUnit/getOrgTreeJson`)
        .then(response => {
          if (response.data.success === true) {
            this.loadingtext = '无匹配数据'
            this.treedata = [response.data.result]
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    getUnitTypeName () {
      if (this.flag === 'admin' || this.flag === 'Admin') {
        this.jgsyCodeMinistry = null
      }
      this.$http
        .get(this.$http.defaults.headcountAPI + 'api/allUnit/getDClassByJgsyCode?jgsyCode=' + this.jgsyCode)
        .then(response => {
          if (response.data.success === true) {
            this.dClass = response.data.result && response.data.result.dclass
            // 如果flag为user的话，之前已经通过getCurrentUnitStatus方法获取到当前用户是司局用户的jgsyCodeMinistry，无需再次获取
            if (this.flag === 'admin' || this.flag === 'Admin') {
              if (this.dClass && this.dClass !== '1e') {
                let arr = response.data.result.jgsyCode.split('-')
                arr.pop()
                this.jgsyCodeMinistry = arr.join('-')
              }
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
      // this.jgsyCodeMinistry = null
      // this.$http
      //   .get(this.$http.defaults.headcountAPI + 'api/busUnit/getUnitTypeName?jgsyCode=' + this.jgsyCode)
      //   .then(response => {
      //     if (response.data.success === true) {
      //       if (response.data.result && response.data.result.unitTypeName === '机关司局') {
      //         let arr = response.data.result.jgsyCode.split('-')
      //         arr.pop()
      //         this.jgsyCodeMinistry = arr.join('-')
      //       }
      //     } else {
      //       console.log('获取失败:' + response.data.message)
      //       this.$message({
      //         message: '获取失败:' + response.data.message,
      //         type: 'error'
      //       })
      //     }
      //   })
      //   .catch(error => {
      //     console.log(error)
      //     this.$message({
      //       message: '获取失败:' + error,
      //       type: 'error'
      //     })
      //   })
    },
    renderContent (h, { node, data, store }) {
      return (
        <span class="custom-tree-node" style="width:100%">
          <i v-show={data.type === 1} class="tree-icon iconfont icon-wenjianjia1 dw3" />
          <i v-show={data.type === 2} class="tree-icon iconfont icon-danwei dw3" />
          <i v-show={data.type === 3} class="tree-icon iconfont icon-cf-c24 dw3" />
          <span style="line-height:28px">{data.name}</span>
        </span>
      )
    },
    // 根据jgsyCode获取节点填报状态
    getStatusByCode () {
      this.isShowText = ''
      this.$http
        .get(this.$http.defaults.headcountAPI + `api/busUnit/getStatusByCode?jgsyCode=${this.jgsyCode}`)
        .then(response => {
          if (response.data.success === true) {
            if (response.data.result === 0) {
              this.isShowText = '（填报中）'
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    // 是否折叠左侧树
    showtree () {
      if (this.treeShow) {
        this.treeShow = false
        this.detailStyle.margin = '0 0 0 10px'
        this.detailStyle.width = 'calc(100% - 20px)'
        this.btnStyle = 'treebtn1'
      } else {
        this.treeShow = true
        this.detailStyle.margin = '0 0 0 280px'
        this.detailStyle.width = 'calc(100% - 290px)'
        this.btnStyle = 'treebtn'
      }
    },
    // 监听点击节点
    currentChangeHandler (row) {
      this.historyTableName = null
      this.infoTableName = null
      this.sourceTable = null
      if (row.type === 1) {
        this.orgName = '请选择单位或部门'
      } else {
        const count = row.allId.split('-').length - 1
        if (row.allId.startsWith(1)) {
          this.infoTableName = 'first'
        } else if (row.allId.startsWith(2)) {
          if (count === 2) {
            this.historyTableName = 'centreDwbd'
            this.infoTableName = 'second'
          } else if (count === 3) {
            this.historyTableName = 'centreSyDwbd'
            this.infoTableName = 'third'
          } else {
            this.historyTableName = null
            this.infoTableName = null
          }
        } else if (row.allId.startsWith(3)) {
          this.historyTableName = 'centreSyDwbd'
          this.infoTableName = 'third'
        }
        this.type = row.type
        this.orgName = row.name
        this.sourceTable = row.sourceTable
        this.jgsyCode = row.jgsyCode
        // if (this.flag === 'admin' || this.flag === 'Admin') {
        this.getUnitTypeName()
        // }
        this.getStatusByCode()
      }
    },
    // 提交
    submit () {
      this.$confirm('确认要提交吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.btnLoading = true
        this.$http
          .post(this.$http.defaults.headcountAPI + `api/busUnit/updateCurrentUnitState`)
          .then(response => {
            if (response.data.success === true) {
              this.btnLoading = false
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.$router.back()
            } else {
              console.log('操作失败:' + response.data.message)
              this.$message({
                message: '操作失败:' + response.data.message,
                type: 'error'
              })
              this.btnLoading = false
            }
          })
          .catch(error => {
            console.log(error)
            this.$message({
              message: '操作失败:' + error,
              type: 'error'
            })
            this.btnLoading = false
          })
      })
    }
  }
}
</script>

<style>
#orgTree i{
  padding-right:5px;
}
#orgTree i.icon-wenjianjia1{
  color: #ffc500 !important;
}
#orgTree i.icon-cf-c24{
  color: #6fb400 !important;
}
#orgTree i.icon-danwei{
  color: #1296db !important;
}
#orgTree{
  width: 260px !important;
  border:1px solid #95B8E7;
  height: calc(100% - 140px);
  background: #fff !important;
  padding-top:0;
  padding-right:0;
  margin-top:0;
  margin-left:10px;
  overflow: hidden;
  float: left;
  position: fixed;
}
.treebtn{
  background:url(../assets/hidetree.png) no-repeat;
  left:273px;
  width:7px;
  height:28px;
  position:fixed;
  top: calc(50%);
  cursor: pointer;
}
.treebtn1{
  background:url(../assets/showtree.png) no-repeat;
  left:3px;
  width:7px;
  height:28px;
  position:fixed;
  top: calc(50%);
  cursor: pointer;
}
#orgdetail{
  background: #fff;
  border:1px solid #95B8E7;
  height: calc(100% - 140px);
  float: left;
  position: fixed;
  padding:0 !important;
}
#orgdetail h1{
  height: 30px;
  border-bottom: 1px solid #95B8E7;
  font-family: '宋体';
  line-height: 30px;
  font-size:var(--size14) !important;
  color: #000;
  padding-left:10px;
  background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
  margin-bottom:0;
}
.el-tree{
  background: #fff;
}
.custom-tree-node {
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
#editswitch{
  margin: 15px;
  text-align: right;
  line-height: 20px;
  font-size: 14px;
}
.treeinput{
  margin: 10px;
  width: 136px !important;
  float:left
}
.orgbuttons{
  float:right;
}
.orgtreebtn{
  float: left;
  margin:10px 10px 0 0 !important;
}
.orgtreebtn{
  padding: 12px 8px 12px 13px !important;
}
#org .el-breadcrumb{
  padding-bottom: 10px;
}
</style>
